package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.exception.DataException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.BeanHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    private static final String LOGIN_PASSWORD_ERROR_KEY = "login:error:";   //密码输入错误标记的 key
    private static final String LOGIN_LOCK_ERROR_KEY = "login:lock:";        //账号被锁定的 key

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    //员工登录
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        // 把从前端获取的密码转成 MD5
        String encodedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // 校验员工账号是否被锁定
        validateAccountLock(username);


        //1. 调用Mapper，查询员工信息
        Employee employee = employeeMapper.findByUsername(employeeLoginDTO.getUsername());

        //2. 判断员工是否存在, 不存在 返回错误信息
        if (employee == null){
            log.info("查询到的员工信息为空，返回错误");
            throw new DataException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //3. 校验密码的正确性，如果不正确，返回错误信息
        if (!employee.getPassword().equals(encodedPassword)){
            log.info("密码比对错误");

            //3.1 记录员工密码错误的标记，并设置有效期为5分钟
            redisTemplate.opsForValue().set(getKey(username), "-", 5, TimeUnit.MINUTES);

            //3.2 获取该员工的密码错误标记，如果标记的数量>=5，设置账号锁定的标记
            Set<Object> keys = redisTemplate.keys(LOGIN_PASSWORD_ERROR_KEY + username + ":*");
            if (keys != null && keys.size() >= 5){
                log.info("员工登录密码5分钟之内，错误次数超过五次，锁定账号一小时");
                redisTemplate.opsForValue().set(LOGIN_LOCK_ERROR_KEY + username, "-", 30, TimeUnit.MINUTES);
                throw new BusinessException(MessageConstant.LOGIN_LOCK_ERROR);
            }

            throw new BusinessException(MessageConstant.PASSWORD_ERROR);
        }

        //4. 校验员工的状态，如果是禁用状态，则返回错误信息
        if (employee.getStatus() == StatusConstant.DISABLE){
            log.info("登录账号 {} 被禁用，禁止登录。", employeeLoginDTO.getUsername());
            throw new DataException(MessageConstant.ACCOUNT_LOCKED);
        }

        return employee;
    }

    //新增员工
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //1. 补全实体属性
        Employee employee = BeanHelper.copyProperties(employeeDTO, Employee.class);

        //1.1 设置密码-加密 默认密码: 123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //1.2 设置状态 默认状态: 启用
        employee.setStatus(StatusConstant.ENABLE);

//        //1.3 设置当前创建时间
//        employee.setCreateTime(LocalDateTime.now());
//
//        //1.4 设置当前修改时间
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //1.5 设置添加当前登录员工id
//        employee.setCreateUser(BaseContext.getCurrentId());
//
//        //1.6 设置修改当前登录员工id
//        employee.setUpdateUser(BaseContext.getCurrentId());

        //2. 调用mapper，保存数据
        employeeMapper.insert(employee);

    }

    // 分页查询
    @Override
    public PageResult page(EmployeePageQueryDTO pageQueryDTO) {
        //1. 设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        //2. 执行查询
        List<Employee> employeeList = employeeMapper.list(pageQueryDTO.getName());

        //3. 解析并封装结果
        Page<Employee> page = (Page<Employee>) employeeList;

        return new PageResult(page.getTotal(), page.getResult());
    }

    // 启用/禁用员工
    @Override
    public void enableOrDisable(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
        employeeMapper.update(employee);
    }

    // 根据id查询员工信息
    @Override
    public Employee queryById(Long id) {
        Employee employee = employeeMapper.queryById(id);
        return employee;
    }

    // 修改员工信息
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = Employee.builder()
                .id(employeeDTO.getId())
                .username(employeeDTO.getUsername())
                .name(employeeDTO.getName())
                .phone(employeeDTO.getPhone())
                .sex(employeeDTO.getSex())
                .idNumber(employeeDTO.getIdNumber())
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }


    // 校验员工账号是否被锁定
    private void validateAccountLock(String username) {
        Object flag = redisTemplate.opsForValue().get(LOGIN_LOCK_ERROR_KEY + username);
        if (ObjectUtils.isNotEmpty(flag)){
            log.info("账号被锁定，限制登录");
            throw new BusinessException(MessageConstant.LOGIN_LOCK_ERROR_MESSAGE);
        }
    }


    //拼接 redis 的 key
    private String getKey(String username) {
        return LOGIN_PASSWORD_ERROR_KEY + username + ":" + RandomStringUtils.randomAlphabetic(5);
    }
}
